package com.appspot.aliga;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.aliga.openligadb.LeagueTableUpdater;
import com.appspot.aliga.openligadb.OpenLigaDBUpdater;
import com.appspot.aliga.persistence.PersistenceService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class BackendUpdateServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		String delete = req.getParameter("cleanDB");
		String updateAll = req.getParameter("updateAll");
		String updateLeagueTable = req.getParameter("updateLeagueTable");
		if ("true".equals(delete)) {
			new PersistenceService().cleanDB();
			resp.setContentType("text/plain");
			resp.getWriter().println("cleaned Database");
		} else if ("true".equals(updateAll)) {
			OpenLigaDBUpdater updater = new OpenLigaDBUpdater();
			updater.updateAllMatches();
			resp.setContentType("text/plain");
			resp.getWriter().println("updated all Matches");
		} else if ("true".equals(updateLeagueTable)) {
			LeagueTableUpdater updater = new LeagueTableUpdater();
			updater.updateAllLeagueTable();
			resp.setContentType("text/plain");
			resp.getWriter().println("updated all LeagueTables");
		} else {
			resp.setContentType("text/plain");

			try {
				URL url = new URL(
						"http://openligadb-json.heroku.com/api/matchdata_by_group_league_saison?group_order_id=20&league_saison=2010&league_shortcut=bl1");
				Gson gson = new GsonBuilder().create();

				Reader reader = new InputStreamReader(url.openStream());

				Object[] gstring = gson.fromJson(reader, Object[].class);
				
				resp.setContentType("text/plain");
				resp.getWriter().println(gstring);

				reader.close();

			} catch (MalformedURLException e) {
				// ...
			} catch (IOException e) {
				// ...
			}

			// OpenLigaDBUpdater updater = new OpenLigaDBUpdater();
			// updater.updateCurrentGameDay();
			//
			// resp.setContentType("text/plain");
			// resp.getWriter().println("updated current Gameday");
		}
	}
}
